package com.cqndt.disaster.device.jdbc.dao;

import com.cqndt.disaster.device.common.util.CamelNamedUtil;
import com.cqndt.disaster.device.datasources.MyJdbcTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Component;

@Component
public class ReciverDao {


    @Autowired
    private MyJdbcTemplate myJdbcTemplate;

    public int autoSave(Object entity){

        String tableName = CamelNamedUtil.camel2Underline(entity.getClass().getSimpleName());

        String columns = "";
        String values = "";
        SqlParameterSource source  = new BeanPropertySqlParameterSource(entity);
        String[] parameterNames =  source.getParameterNames();
        for (int i=0;i<parameterNames.length; i++){

            String parameter = parameterNames[i];

            if(!"class".equals(parameter)){
                columns+=CamelNamedUtil.camel2Underline(parameter);
                values+=":"+parameter;

                if(i<parameterNames.length-1){
                    columns+=",";
                    values+=",";
                }
            }

        }

        String sql = "INSERT INTO "+tableName+" ("+columns+") VALUES ("+values+")";
        System.out.println(sql);
        KeyHolder keyHolder = new GeneratedKeyHolder();
        myJdbcTemplate.update(sql, source, keyHolder);
        Integer num = keyHolder.getKey().intValue();

        return num;
    }
}
